<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import { useRouter } from 'vue-router'
import {
  NAvatar,
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect,
  NSelect,
  NFlex,
  NCard,
  NDivider,
  NIcon,
  NModal,
  NRadio,
  NRadioGroup,
  NInputNumber
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import {formatDate, getToken, renderIcon} from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'

defineOptions({ name: '问卷管理' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')

// 问卷编辑相关状态
const surveyEditVisible = ref(false)
const surveyEditMode = ref('add') // add, edit, preview
const currentSurvey = ref({
  id: null,
  name: '',
  info: []
})

// 项目类型选项
const questionTypes = [
  { label: '填空项', value: 1 },
  { label: '单选项', value: 2 },
  { label: '多选项', value: 3 }
]

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '问卷',
  initForm: {},
  doCreate: api.createSurvey,
  doUpdate: api.updateSurvey,
  doDelete: api.deleteSurvey,
  refresh: () => $table.value?.handlerefresh(),
})

onMounted(() => {
  $table.value?.handleSearch()
})

const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '问卷名称',
    key: 'name',
    width: 200,
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
  },
  {
    title: '项目数量',
    key: 'question_count',
    width: 100,
    align: 'center',
    render(row) {
      try {
        const parsedInfo = JSON.parse(row.info || '[]')
        if (Array.isArray(parsedInfo)) {
          return parsedInfo.length
        } else if (parsedInfo && parsedInfo.questions && Array.isArray(parsedInfo.questions)) {
          return parsedInfo.questions.length
        }
        return 0
      } catch (error) {
        return 0
      }
    }
  },
  {
    title: '创建时间',
    key: 'created_at',
    width: 150,
    align: 'center',
    render(row) {
      return formatDate(row.created_at)
    }
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'info',
              style: 'margin-right: 8px;',
              onClick: () => {
                handlePreview(row)
              },
            },
            {
              default: () => '预览',
              icon: renderIcon('material-symbols:visibility', { size: 16 }),
            }
          ),
          []
        ),
        // withDirectives(
        //   h(
        //     NButton,
        //     {
        //       size: 'small',
        //       type: 'success',
        //       style: 'margin-right: 8px;',
        //       onClick: () => {
        //         handleViewResults(row)
        //       },
        //     },
        //     {
        //       default: () => '查看结果',
        //       icon: renderIcon('material-symbols:analytics', { size: 16 }),
        //     }
        //   ),
        //   []
        // ),
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                handleSurveyEdit(row)
              },
            },
            {
              default: () => '编辑',
              icon: renderIcon('material-symbols:edit', { size: 16 }),
            }
          ),
          []
        ),
        h(
          NPopconfirm,
          {
            onPositiveClick: () => handleDelete({ id: row.id }, false),
            onNegativeClick: () => {},
          },
          {
            trigger: () =>
              withDirectives(
                h(
                  NButton,
                  {
                    size: 'small',
                    type: 'error',
                  },
                  {
                    default: () => '删除',
                    icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                  }
                ),
                []
              ),
            default: () => h('div', {}, '确定删除吗?'),
          }
        ),
      ]
    },
  },
]

// 预览问卷
function handlePreview(row) {
  let info = []
  try {
    const parsedInfo = JSON.parse(row.info || '[]')
    // 确保info是数组格式
    if (Array.isArray(parsedInfo)) {
      info = parsedInfo
    } else if (parsedInfo && parsedInfo.questions && Array.isArray(parsedInfo.questions)) {
      // 如果是旧格式 {questions: [...]}，提取questions数组
      info = parsedInfo.questions
    } else {
      info = []
    }
  } catch (error) {
    console.error('解析问卷数据失败:', error)
    info = []
  }
  
  // 确保每个项目都有options字段
  const processedInfo = info.map(question => ({
    ...question,
    options: question.options || []
  }))
  
  currentSurvey.value = {
    id: row.id,
    name: row.name,
    info: processedInfo
  }
  surveyEditMode.value = 'preview'
  surveyEditVisible.value = true
}

// 查看问卷结果
// function handleViewResults(row) {
//   // 跳转到问卷结果页面
//   const router = useRouter()
//   router.push({
//     name: '问卷结果',
//     params: { surveyId: row.id }
//   })
// }

// 编辑问卷
function handleSurveyEdit(row) {
  let info = []
  try {
    const parsedInfo = JSON.parse(row.info || '[]')
    // 确保info是数组格式
    if (Array.isArray(parsedInfo)) {
      info = parsedInfo
    } else if (parsedInfo && parsedInfo.questions && Array.isArray(parsedInfo.questions)) {
      // 如果是旧格式 {questions: [...]}，提取questions数组
      info = parsedInfo.questions
    } else {
      info = []
    }
  } catch (error) {
    console.error('解析问卷数据失败:', error)
    info = []
  }
  
  // 确保每个项目都有options字段
  const processedInfo = info.map(question => ({
    ...question,
    options: question.options || []
  }))
  
  currentSurvey.value = {
    id: row.id,
    name: row.name,
    info: processedInfo
  }
  surveyEditMode.value = 'edit'
  surveyEditVisible.value = true
}

// 新增问卷
function handleSurveyAdd() {
  currentSurvey.value = {
    id: null,
    name: '',
    info: []
  }
  surveyEditMode.value = 'add'
  surveyEditVisible.value = true
}

// 添加项目
function addQuestion() {
  const newQuestion = {
    id: Date.now(),
    type: 1, // 默认填空项
    title: '',
    options: [],
    required: true
  }
  currentSurvey.value.info.push(newQuestion)
}

// 删除项目
function removeQuestion(index) {
  currentSurvey.value.info.splice(index, 1)
}

// 添加选项
function addOption(questionIndex) {
  const question = currentSurvey.value.info[questionIndex]
  if (!question.options) {
    question.options = []
  }
  question.options.push({ text: '' })
}

// 删除选项
function removeOption(questionIndex, optionIndex) {
  const question = currentSurvey.value.info[questionIndex]
  if (!question.options) {
    question.options = []
  }
  question.options.splice(optionIndex, 1)
}

// 保存问卷
async function saveSurvey() {
  if (!currentSurvey.value.name.trim()) {
    $message.error('请输入问卷名称')
    return
  }

  // 验证项目
  for (let i = 0; i < currentSurvey.value.info.length; i++) {
    const question = currentSurvey.value.info[i]
    if (!question.title.trim()) {
      $message.error(`${i + 1}项标项不能为空`)
      return
    }

    // 单选项和多选项需要至少一个选项
    if ((question.type === 2 || question.type === 3) && question.options.length === 0) {
      $message.error(`${i + 1}项需要至少一个选项`)
      return
    }

    // 验证选项内容
    for (let j = 0; j < question.options.length; j++) {
      if (!question.options[j].text.trim()) {
        $message.error(`${i + 1}项${j + 1}个选项不能为空`)
        return
      }
    }
  }

  try {
    const surveyData = {
      name: currentSurvey.value.name,
      info: JSON.stringify(currentSurvey.value.info)
    }

    if (surveyEditMode.value === 'add') {
      await api.createSurvey(surveyData)
      $message.success('问卷创建成功')
    } else if (surveyEditMode.value === 'edit') {
      await api.updateSurvey({ ...surveyData, id: currentSurvey.value.id })
      $message.success('问卷更新成功')
    }

    surveyEditVisible.value = false
    $table.value?.handlerefresh()
  } catch (error) {
    console.error('保存问卷失败:', error)
  }
}

// 问卷答案（预览模式用）
const surveyAnswers = ref([])

// 提交问卷答案（预览模式）
function submitSurvey() {
  const answers = []
  currentSurvey.value.info.forEach((question, index) => {
    if (question.type === 1) {
      // 填空项
      answers.push(surveyAnswers.value[index] || '')
    } else if (question.type === 2) {
      // 单选项
      answers.push(surveyAnswers.value[index] || '')
    } else if (question.type === 3) {
      // 多选项
      answers.push(surveyAnswers.value[index] || [])
    }
  })

  console.log('问卷答案:', answers)
  $message.success('问卷提交成功')
  surveyEditVisible.value = false
}

// 表单验证规则
const validateSurveyForm = {
  name: [
    { required: true, message: '请输入问卷名称', trigger: 'blur' }
  ]
}
</script>

<template>
  <NLayout has-sider wh-full>
    <NLayoutContent style="background: transparent;margin-left: 20px;margin-top: 100px">
      <CommonPage show-footer title="问卷管理">
        <template #action>
          <NButton type="primary" @click="handleSurveyAdd">
            <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建问卷
          </NButton>
        </template>

        <!-- 表格 -->
        <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="api.getSurveys"
          :scroll-x="1200"
        >
          <template #queryBar>
            <QueryBarItem label="问卷名称" :label-width="90">
              <NInput
                v-model:value="queryItems.name"
                clearable
                type="text"
                placeholder="请输入问卷名称"
                @keypress.enter="$table?.handleSearch()"
              />
            </QueryBarItem>
          </template>
        </CrudTable>
      </CommonPage>
    </NLayoutContent>
  </NLayout>

  <!-- 问卷编辑弹窗 -->
  <NModal
    v-model:show="surveyEditVisible"
    :title="surveyEditMode === 'preview' ? '问卷预览' : (surveyEditMode === 'add' ? '新建问卷' : '编辑问卷')"
    preset="card"
    style="width: 90%; max-width: 1200px;"
    :mask-closable="false"
  >
    <div style="max-height: 80vh; overflow-y: auto;">
      <!-- 问卷基本信息 -->
      <NCard v-if="surveyEditMode !== 'preview'" title="基本信息" style="margin-bottom: 20px;">
          <NForm :model="currentSurvey" :rules="validateSurveyForm" ref="surveyFormRef">
            <NFormItem label="问卷名称" path="name">
              <NInput v-model:value="currentSurvey.name" placeholder="请输入问卷名称" />
            </NFormItem>
          </NForm>
      </NCard>

      <!-- 问卷预览信息 -->
      <NCard v-if="surveyEditMode === 'preview'" style="margin-bottom: 20px;">
        <h3>{{ currentSurvey.name }}</h3>
      </NCard>

      <!-- 项目列表 -->
      <NCard title="项目设置" style="margin-bottom: 20px;">
        <div v-if="currentSurvey.info.length === 0" style="text-align: center; padding: 40px; color: #999;">
          暂无项目，请添加项目
        </div>

        <div v-for="(question, questionIndex) in currentSurvey.info" :key="question.id"
             style="margin-bottom: 30px; padding: 20px; border: 1px solid #e0e0e0; border-radius: 8px;">

          <!-- 项目头部 -->
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
            <div style="display: flex; align-items: center; gap: 10px;">
              <span style="font-weight: bold;">{{ questionIndex + 1 }}项</span>
              <NSelect
                v-if="surveyEditMode !== 'preview'"
                v-model:value="question.type"
                :options="questionTypes"
                label-field="label"
                value-field="value"
                style="width: 120px;"
              />
              <NSwitch
                v-if="surveyEditMode !== 'preview'"
                v-model:value="question.required"
                checked-value="必填"
                unchecked-value="选填"
              />
              <span style="font-size: 12px; color: #666;">
                {{ question.required ? '必填' : '选填' }}
              </span>
            </div>
            <NButton
              v-if="surveyEditMode !== 'preview'"
              size="small"
              type="error"
              @click="removeQuestion(questionIndex)"
            >
              删除项目
            </NButton>
          </div>

          <!-- 项目标项 -->
          <NFormItem label="项目内容">
            <NInput
              v-if="surveyEditMode !== 'preview'"
              v-model:value="question.title"
              placeholder="请输入项目内容"
            />
            <div v-else style="font-weight: bold; margin-bottom: 10px;">
              {{ question.title }}
              <span style="color: red;">{{ question.required ? '*' : '' }}</span>
            </div>
          </NFormItem>

          <!-- 填空项 -->
          <div v-if="question.type == 1">
            <NFormItem label="答案">
              <NInput
                type="textarea"
                v-if="surveyEditMode === 'preview'"
                v-model:value="surveyAnswers[questionIndex]"
                placeholder="请输入答案"
                :rows="3"
              />
              <div v-else style="color: #666; font-size: 14px;">
                填空项，用户可自由输入文本内容
              </div>
            </NFormItem>
          </div>

          <!-- 单选项 -->
          <div v-if="question.type == 2">
            <NFormItem label="选项设置">
              <div v-if="surveyEditMode !== 'preview'">
                <div v-for="(option, optionIndex) in question.options" :key="optionIndex"
                     style="display: flex; align-items: center; margin-bottom: 10px;">
                  <NRadio :value="optionIndex" style="margin-right: 10px;" />
                  <NInput
                    v-model:value="option.text"
                    placeholder="请输入选项内容"
                    style="flex: 1; margin-right: 10px;"
                  />
                  <NButton size="small" type="error" @click="removeOption(questionIndex, optionIndex)">
                    删除
                  </NButton>
                </div>
                <NButton size="small" type="primary" @click="addOption(questionIndex)">
                  添加选项
                </NButton>
              </div>
              <div v-else>
                <NRadioGroup v-model:value="surveyAnswers[questionIndex]">
                  <div v-for="(option, optionIndex) in question.options" :key="optionIndex"
                       style="margin-bottom: 8px;">
                    <NRadio :value="optionIndex" :label="option.text" />
                  </div>
                </NRadioGroup>
              </div>
            </NFormItem>
          </div>

          <!-- 多选项 -->
          <div v-if="question.type == 3">
            <NFormItem label="选项设置">
              <div v-if="surveyEditMode !== 'preview'">
                <div v-for="(option, optionIndex) in question.options" :key="optionIndex"
                     style="display: flex; align-items: center; margin-bottom: 10px;">
                  <NCheckbox :value="optionIndex" style="margin-right: 10px;" />
                  <NInput
                    v-model:value="option.text"
                    placeholder="请输入选项内容"
                    style="flex: 1; margin-right: 10px;"
                  />
                  <NButton size="small" type="error" @click="removeOption(questionIndex, optionIndex)">
                    删除
                  </NButton>
                </div>
                <NButton size="small" type="primary" @click="addOption(questionIndex)">
                  添加选项
                </NButton>
              </div>
              <div v-else>
                <NCheckboxGroup v-model:value="surveyAnswers[questionIndex]">
                  <div v-for="(option, optionIndex) in question.options" :key="optionIndex"
                       style="margin-bottom: 8px;">
                    <NCheckbox :value="optionIndex" :label="option.text" />
                  </div>
                </NCheckboxGroup>
              </div>
            </NFormItem>
          </div>
        </div>

        <!-- 添加项目按钮 -->
        <div v-if="surveyEditMode !== 'preview'" style="text-align: center; margin-top: 20px;">
          <NButton type="primary" @click="addQuestion">
            <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />添加项目
          </NButton>
        </div>
      </NCard>
    </div>

    <!-- 底部操作按钮 -->
    <template #footer>
      <div style="display: flex; justify-content: flex-end; gap: 10px;">
        <NButton @click="surveyEditVisible = false">
          {{ surveyEditMode === 'preview' ? '关闭' : '取消' }}
        </NButton>
        <NButton v-if="surveyEditMode === 'preview'" type="primary" @click="submitSurvey">
          提交问卷
        </NButton>
        <NButton v-else type="primary" @click="saveSurvey">
          {{ surveyEditMode === 'add' ? '创建' : '保存' }}
        </NButton>
      </div>
    </template>
  </NModal>
</template>
